<template>
  <div class="container">
    <h3>用户列表</h3>
    <el-form :inline="true">
      <el-form-item label="关键字" size="small">
        <el-input v-model="keyword" placeholder="用户名/手机号" />
      </el-form-item>
      <el-form-item size="small">
        <el-button
          type="primary"
          :disabled="!$hasBP('bnt.sysUser.list')"
          @click="searchUsers"
        >
          查询
        </el-button>
      </el-form-item>
      <el-form-item size="small">
        <el-button
          type="primary"
          @click="
            () => {
              keyword = '';
              searchUsers();
            }
          "
        >
          重置
        </el-button>
      </el-form-item>
      <el-form-item size="small">
        <el-button
          type="success"
          :disabled="!$hasBP('bnt.sysUser.add')"
          @click="clickAddUser"
        >
          添加
        </el-button>
      </el-form-item>
      <el-form-item size="small">
        <el-popconfirm
          title="确定批量删除吗？"
          @onConfirm="batchDeleteByUserIds()"
        >
          <el-button
            slot="reference"
            type="danger"
            :disabled="
              !$hasBP('bnt.sysUser.batchRemove') || selectedIds.length === 0
            "
          >
            批量删除
          </el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <el-dialog
      :title="userInfoDialogType === 'add' ? '添加' : '编辑'"
      :visible="userInfoDialogType !== ''"
      width="30%"
      @close="userInfoDialogType = ''"
    >
      <el-form label-position="left" label-width="80px" :model="user">
        <el-form-item label="账号">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="user.name" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="user.password" show-password />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="user.phone" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="user.description" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="user.status"
            active-text="正常"
            :active-value="1"
            :inactive-value="0"
            inactive-text="冻结"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userInfoDialogType = ''">取 消</el-button>
        <el-button type="primary" @click="userAction()"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="角色分配"
      width="30%"
      :visible="showAssignRoleDialog"
      @close="showAssignRoleDialog = false"
    >
      <el-form label-position="left" label-width="80px" :model="user">
        <el-form-item label="账号">
          <el-input v-model="user.username" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox-group v-model="checkedRoleIds">
            <el-checkbox
              v-for="role in allRoles"
              :key="role.id"
              :label="role.id"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAssignRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="assignRoles"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      :v-loading="listLoading"
      element-loading-text="Loading"
      @select="handleTableSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ limit * (page - 1) + 1 + scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="账号">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="真实姓名">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="手机号">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="描述">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="70px">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="(v) => changeStatus(scope.row.id, v)"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            style="width: 40px; margin-right: 5px"
            :disabled="!$hasBP('bnt.sysUser.update')"
            @click="clickUpdateUser(scope.row)"
          >
            <i class="el-icon-edit" style="color: white" />
          </el-button>
          <DeleteBtn
            :disabled="!$hasBP('bnt.sysUser.remove')"
            @deleteItem="deleteByUserId(scope.row.id)"
          />
          <el-button
            type="warning"
            size="small"
            style="width: 40px"
            :disabled="!$hasBP('bnt.sysUser.assignRole')"
            @click="clickAssignRole(scope.row)"
          >
            <i class="el-icon-s-check" style="color: white" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 5px 10px; display: flex; justify-content: center">
      <el-pagination
        :current-page="page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import {
  getPageList,
  deleteById,
  add,
  updateById,
  batchDelete,
  updateStatus,
} from "@/api/system/user";
import { queryRoleById, doAssignRole } from "@/api/system/role";
import DeleteBtn from "@/components/tools/DeleteBtn";

export default {
  components: { DeleteBtn },
  // 定义初始值
  data() {
    return {
      listLoading: true,
      list: [], // 用户列表
      total: 0, // 总记录数
      page: 1, // 当前页
      limit: 5, // 每页显示记录数
      searchObj: {}, // 条件查询封装对象
      keyword: "",
      userInfoDialogType: "",
      user: {},
      selectedIds: [],
      showAssignRoleDialog: false,
      allRoles: [],
      checkedRoleIds: [],
    };
  },
  // 页面渲染之前执行
  created() {
    this.fetchData();
  },
  methods: {
    // 具体方法
    fetchData(pageNum = 1) {
      this.listLoading = true;
      // 发送 ajax 请求
      this.page = pageNum;
      getPageList(this.page, this.limit, this.searchObj)
        .then((response) => {
          this.list = response.data.records;
          this.total = response.data.total;
          // this.listLoading = false;
        })
        .catch(() => {
          // this.listLoading = false;
        });
    },
    handleSizeChange(val) {
      this.limit = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.fetchData(val);
    },
    searchUsers() {
      this.searchObj = {};
      if (this.keyword) {
        this.searchObj.keyword = this.keyword;
      }
      this.fetchData();
    },
    deleteByUserId(id) {
      deleteById(id).then(() => {
        this.fetchData();
      });
    },
    clickAddUser() {
      this.userInfoDialogType = "add";
      this.user = {
        status: 1,
      };
    },
    updateUserInfoById(userInfo) {
      updateById(userInfo).then(() => {
        this.fetchData();
      });
    },
    userAction() {
      if (this.userInfoDialogType === "add") {
        add(this.user).then(() => {
          this.fetchData();
        });
      } else if (this.userInfoDialogType === "edit") {
        this.updateUserInfoById(this.user);
      }
      this.userInfoDialogType = "";
    },
    clickUpdateUser(user) {
      this.userInfoDialogType = "edit";
      this.user = {
        id: user.id,
        username: user.username,
        name: user.name,
        phone: user.phone,
        description: user.description,
        status: user.status,
      };
    },
    handleTableSelectionChange(rows) {
      this.selectedIds = rows.map((e) => e.id);
    },
    batchDeleteByUserIds() {
      batchDelete(this.selectedIds).then(() => {
        this.selectedIds = [];
        this.fetchData();
      });
    },
    changeStatus(id, status) {
      // this.updateUserInfoById({ id, status });
      console.log("id = ", id, "status = ", status);
      updateStatus(id, status).then(() => {
        this.fetchData();
      });
    },
    clickAssignRole(user) {
      this.user = user;
      this.checkedRoleIds = [];
      queryRoleById(user.id).then((res) => {
        this.allRoles = res.data.allRoles;
        this.checkedRoleIds = res.data.userRoleIds;
      });
      this.showAssignRoleDialog = true;
    },
    assignRoles() {
      doAssignRole({
        userId: this.user.id,
        roleIdList: this.checkedRoleIds,
      }).then(() => {
        this.showAssignRoleDialog = false;
        this.$message({
          message: "用户角色更新成功",
          type: "success",
        });
      });
    },
  },
};
</script>

<style scoped>
.container {
  padding: 5px 10px;
}
</style>
